﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using System.Data;
using JKF.Entities.Model;
namespace JKF.HandlerLayer.Product
{
   public partial class ProductHandler:AHttpHandler
    {
       private static bllPRODUCT bllProduct = new bllPRODUCT();
       public override void ProcessRequest()
       {
           //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
           try
           {
               this.Manager(Utils.GetActionName);
           }
           catch (Exception ex)
           {
               //将错误抛到客户端(以Json格式)
               Utils.ToClient(true, ex.Message);
               //写日志
               AppLogger.Log(ex.Message, ex);
           }
       }
       /// <summary>
       /// 添加产品
       /// </summary>
       public void InsertProduct()
       {
           try
           {
               var strScr = P("moduleObj");
               var productInfo = this.BuildProduct_SortinfoByJson(JsonSerializer.Deserialize<ProductTemp>(strScr), false);
               string insertProductSql = string.Format(@"
INSERT INTO dbo.PRODUCT(PRODUCT_KEY, SORT_KEY, NAME, MODEL, RETAIL_PRICE, PURCHASE_PRICE, TYPE, DESCRIPTION, SHOP_CODE, USER_CREATE, DATE_CREATE,LIFE_LENGTH) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", productInfo.PRODUCT_KEY.ToString(), productInfo.SORT_KEY.ToString(), productInfo.NAME, productInfo.MODEL, productInfo.RETAIL_PRICE, productInfo.PURCHASE_PRICE, productInfo.TYPE, productInfo.DESCRIPTION, productInfo.SHOP_CODE, productInfo.USER_CREATE.ToString(), productInfo.DATE_CREATE, productInfo.LIFE_LENGTH == "" ? 0 : Int32.Parse(productInfo.LIFE_LENGTH.Trim()));
               //如果当前角色名称是总店，则赋值为null
               SYS_ROLEinfo roleInfo = new bllSYS_ROLE().GetModel(bllSYS_USER.CurrentUser.ROLE_KEY);
               if (SysConfig.HeadShop.Contains(roleInfo.ROLE_NAME))
               {//如果是总店创建，则重新生成Insert语句
                   insertProductSql = string.Format(@"
INSERT INTO dbo.PRODUCT(PRODUCT_KEY, SORT_KEY, NAME, MODEL, RETAIL_PRICE, PURCHASE_PRICE, TYPE, DESCRIPTION, SHOP_CODE, USER_CREATE, DATE_CREATE,LIFE_LENGTH) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',null,'{8}','{9}','{10}')", productInfo.PRODUCT_KEY.ToString(), productInfo.SORT_KEY.ToString(), productInfo.NAME, productInfo.MODEL, productInfo.RETAIL_PRICE, productInfo.PURCHASE_PRICE, productInfo.TYPE, productInfo.DESCRIPTION, productInfo.USER_CREATE.ToString(), productInfo.DATE_CREATE, productInfo.LIFE_LENGTH);
               }
               //执行插入
               bool result =  bllProduct.ProductSQLBLL(insertProductSql); 
                //bllProduct.Add(productInfo);
                var pk = productInfo.PRODUCT_KEY.ToString();
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "添加成功.", Data = pk }));
               
           }
           catch (Exception exp)
           {
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
           }
       }
       /// <summary>
       /// 编辑产品
       /// </summary>
       public void EditProduct()
       {
           try
           {
               var strScr = P("moduleObj");
               
               var productInfo = this.BuildProduct_SortinfoByJson(JsonSerializer.Deserialize<ProductTemp>(strScr), true);
               // 先判断是否有修改的权限
               SYS_ROLEinfo roleInfo = new bllSYS_ROLE().GetModel(bllSYS_USER.CurrentUser.ROLE_KEY);
               //先获取到产品数据
               PRODUCTinfo productModifyInfo = bllProduct.GetModel(productInfo.PRODUCT_KEY);
               if (SysConfig.HeadShop.Contains(roleInfo.ROLE_NAME) && string.IsNullOrEmpty(productModifyInfo.SHOP_CODE))
               {
                   UpdateProductAction(productInfo);
               }
               else if (!string.IsNullOrEmpty(productModifyInfo.SHOP_CODE))
               {
                   //如果修改的产品的SHOP_CODE不为null，则可以修改
                   UpdateProductAction(productInfo);
               }
               else
               {
                   Response.Write(JsonSerializer.Serialize(
                       new ResponseInf { MessageCode = "No", Message = "总店创建产品,分店不允许修改！" }));
                   return;
               } 
           }
           catch (Exception exp)
           {
               Response.Write(JsonSerializer.Serialize(
                   new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
           }
       }
       /// <summary>
       /// 执行更新产品
       /// </summary>
       /// <param name="productInfo"></param>
       private void UpdateProductAction(ProductTemp productInfo)
       {
           string updateProductSql = string.Format(@"
UPDATE dbo.PRODUCT SET SORT_KEY='{0}',NAME='{1}',MODEL='{2}',RETAIL_PRICE='{3}',
  PURCHASE_PRICE='{4}',TYPE='{5}',DESCRIPTION='{6}',DATE_UPDATE='{7}',LIFE_LENGTH={9} WHERE PRODUCT_KEY='{8}'", productInfo.SORT_KEY.ToString(), productInfo.NAME, productInfo.MODEL, productInfo.RETAIL_PRICE, productInfo.PURCHASE_PRICE, productInfo.TYPE, productInfo.DESCRIPTION, productInfo.DATE_UPDATE, productInfo.PRODUCT_KEY, productInfo.LIFE_LENGTH == "" ? 0 : Int32.Parse(productInfo.LIFE_LENGTH));
           //执行插入
           bool result = bllProduct.ProductSQLBLL(updateProductSql);
           //bllProduct.Add(productInfo);
           var pk = productInfo.PRODUCT_KEY.ToString();
           Response.Write(JsonSerializer.Serialize(
               new ResponseInf { MessageCode = "Ok", Message = "修改成功.", Data = pk }));
       }
       /// <summary>
       /// 从Json对象构建对象
       /// </summary>
       /// <param name="shopInfo">实体对象</param>
       /// <param name="isEdit">是否为编辑</param>
       /// <returns></returns>
       public ProductTemp BuildProduct_SortinfoByJson(ProductTemp productInfo, bool isEdit)
       {
           var entity = new ProductTemp();
           if (!isEdit) // 添加
           {
               entity.PRODUCT_KEY = new Guid(DB.GetNewGuid(DB.HR)); //Guid.NewGuid();
           }
           else // 修改
           {
               entity.PRODUCT_KEY = productInfo.PRODUCT_KEY;
           }
           entity.NAME = productInfo.NAME;
           entity.TYPE = productInfo.TYPE;
           entity.RETAIL_PRICE = productInfo.RETAIL_PRICE;
           entity.PURCHASE_PRICE = productInfo.PURCHASE_PRICE;
           entity.MODEL = productInfo.MODEL;
           entity.SORT_KEY = productInfo.SORT_KEY;
           entity.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE; //当前用户店面编码
           entity.LIFE_LENGTH = productInfo.LIFE_LENGTH;
           entity.DESCRIPTION = productInfo.DESCRIPTION; //备注信息
           entity.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY; // 获取当前用户guid
           entity.DATE_CREATE = System.DateTime.Now;
           entity.DATE_UPDATE = System.DateTime.Now;
           return entity;
       }
       /// <summary>
       /// 获取产品数据列表
       /// </summary>
       public void GetProducts()
       {
           var obj = new PagerList();

           int pageCount = 0;
           int rowCount = 0;
           if (P("isExport") == "1")
           {//产品名称	规格/型号	所属类别	零售价格	进货价格	录入日期

               DataTable dt = bllProduct.GetProductsBLL(bllSYS_USER.CurrentUser, P("TYPE"), P("NAME"), P("MODEL"), P("PageIndex").ToInt32(), -1, ref pageCount, ref rowCount);

               IDictionary<string, string> columns = new Dictionary<string, string>();

               columns.Add("NAME", "产品名称");
               columns.Add("MODEL", "规格/型号");
               columns.Add("SORT_KEY", "所属类别");
               columns.Add("RETAIL_PRICE", "零售价格");
               columns.Add("PURCHASE_PRICE", "进货价格");
               columns.Add("DATE_CREATE", "录入日期");
               //columns.Add("MEMO", "备注");
               Excel.Export("产品、配件设置", dt, columns, Response, Excel.PageType.handler);
           }
           else
           {
               obj.Entity = from a in bllProduct.GetProductsBLL(bllSYS_USER.CurrentUser, P("TYPE"), P("NAME"), P("MODEL"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                            select new
                            {
                                PRODUCT_KEY = a.Field<Guid>("PRODUCT_KEY"),
                                SORT_KEY = a.Field<string>("SORT_KEY"), //所属类别
                                NAME = a.Field<string>("NAME"), //名称
                                MODEL = a.Field<string>("MODEL"), //型号/规格
                                RETAIL_PRICE = a.Field<decimal>("RETAIL_PRICE"), //零售价
                                PURCHASE_PRICE = a.Field<decimal>("PURCHASE_PRICE"), //进货价
                                TYPE = a.Field<string>("TYPE"), //产品分类
                                DATE_CREATE = (a.Field<DateTime>("DATE_CREATE")).ToString("yyyy-MM-dd")
                                //DESCRIPTION = a.Field<string>("DESCRIPTION") //描述
                            };

               obj.RowCount = rowCount;
               obj.PageCount = pageCount;
               ResponseJsonObject = obj;
           }
       }
       /// <summary>
       /// 删除产品
       /// </summary>
       public void DeleteProduct()
       {
           try
           {
               var product_key = P("id");
               //int reslt = 0;
               string strReslt = bllProduct.TransactionSQLDeleteBLL(bllSYS_USER.CurrentUser.USER_KEY, new Guid(product_key));
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = strReslt,Message=strReslt, Data = product_key }));
               
           }
           catch (Exception exp)
           {
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
           }
       }
       /// <summary>
       /// 根据当前ID获取产品
       /// </summary>
       public void GetProductByCode()
       {
           try
           {
               var scid = P("moduleKey"); 
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllProduct.GetModel(new Guid(scid)) }));
           }
           catch (Exception exp)
           {
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
           }
       }
       /// <summary>
       /// 检查名称是否存在
       /// </summary>
       public void CheckProductName()
       {
           try
           {
               var product_name = P("PRODUCT_NAME");
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllProduct.ExistsProductNameBLL(product_name) }));
           }
           catch (Exception exp)
           {
               Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
           }
       }
       /// <summary>
       /// 根据Sort_KEY获取产品数据
       /// </summary>
       public void GetProductBySort_Key()
       {
           try
           {
               var sort_key = P("SORT_KEY");
               List<PRODUCTinfo> oList = bllProduct.GetListArray(string.Format(" SORT_KEY='{0}'", sort_key));
               var sb = new StringBuilder();
               if (oList.Count == 0)
               {
                   sb.AppendFormat("<option value=\"{0}\">{1}</option>", "-1", "此类别下无产品,请先录入！");
               }
               else
               {
                   sb.AppendFormat("<option value=\"{0}\">{1}</option>", "-1", "请选择");
                   foreach (var item in oList)
                   {
                       sb.AppendFormat("<option value=\"{0}\"  model='{1}'>{2}</option>", item.PRODUCT_KEY, item.MODEL, item.NAME);
                   }
               }
               Utils.ToClient(false, sb.ToString());
           }
           catch (Exception ex)
           {
               Utils.ToClient(true, ex.Message);
           } 
             
       }  
       /// <summary>
       /// 此类用于前台传递JSON数据
       /// </summary>
       public class ProductTemp  
       {
           public Guid  PRODUCT_KEY{get;set;}
           public Guid SORT_KEY { get; set; }
           public string NAME { get; set; }
           public string MODEL { get; set; }
           public string RETAIL_PRICE { get; set; }
           public string PURCHASE_PRICE { get; set; }
           public string TYPE { get; set; }
           public string LIFE_LENGTH { get; set; }
           public string DESCRIPTION { get; set; }
           public string SHOP_CODE { get; set; }
           public Guid USER_CREATE { get; set; }
           public DateTime DATE_CREATE{get;set;}
           public DateTime DATE_UPDATE { get; set; }
       }
    }
}
